# -*- coding: latin-1 -*-
# Copyright (c) 2007-2009 Jorge Ortiz Romo <jortizromo@gmail.com>
#                         Freymam Vallejo Cuero <freturn@gmail.com>
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following
# conditions:

# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
# Import the module and instantiate a pygraph object

'''
Created on 16/02/2010
@author: Usuario
'''

import os
from xml.dom import minidom
from xml.parsers import expat as XmlException
import datetime

from settings import DIRS

def loadLogToActivity(filename):
    
    #filename = 'raws/' + filename + '.xml'
    filename = DIRS["TEAMQUEST_MEDIA_ROOT"] + filename + '.xml'
    mapping = []
    print 'reading', filename, '...'
    
    # verifica existencia del archivo
    #if os.path.isfile(os.path.join(os.getcwd(), filename)):
    if os.path.isfile(filename):
        
        # abre el archivo
        try: datas = minidom.parse(filename)
        except XmlException.ExpatError: raise Exception, 'Error parseando el archivo %s' % filename
        except: raise Exception, "Error inesperado intentando datas = minidom.parse(%s)" % (filename)
        
        tags = ["sender", "sender_type", "sender_role", "sender_group", "sender_weight", 
                 "receiver", "receiver_type", "receiver_role", "receiver_group", "receiver_weight", 
                 "activity", "type", "subtype", "action_weight", "datetime", "channel", 
                 "type", "event_weight"]
        
        for situation in datas.getElementsByTagName("situation"):
            row = {}
            for tag in tags:
                for element in situation.getElementsByTagName(tag):
                    for value in element.childNodes:
                        row[tag] = str(value.data)
            mapping.append(row)
        
    return mapping
    

def saveLogToActivity(filename, datas):
    
    #filename = "../analysis/datos/" + filename + ".xml"
    filename = DIRS["CORE_MEDIA_ROOT"] + filename + '.xml'
    session = '-1'
    users_added = []
    objects_added = []
    events_added = []
    print 'saving', filename, '...'
    
    xml = minidom.Document()
    node_situation = xml.createElement("situation")
    node_activity = None
    #node_activity = xml.createElement("activity")
    node_users = None
    node_objects = None
    node_actions = None
    node_events = None

    for data in datas:
        activity = session
        try: activity = data["activity"]
        except: None
        if session != '-1' and session != activity: #data["activity"]:
            if node_users is not None: node_activity.appendChild(node_users)
            if node_objects is not None: node_activity.appendChild(node_objects)
            if node_actions is not None: node_activity.appendChild(node_actions)
            if node_events is not None: node_activity.appendChild(node_events)
            node_situation.appendChild(node_activity)
        if session == '-1' or session != activity: #data["activity"]:
            try: session = data["activity"]
            except: None
            node_activity = xml.createElement("activity")
            node_activity.setAttribute("session", session) #data["activity"])
            node_users = xml.createElement("users")
            node_objects = xml.createElement("objects")
            node_actions = xml.createElement("actions")
            node_events = xml.createElement("events")
            users_added = []
            objects_added = []
            events_added = []
        
        
        if not users_added.__contains__(data["sender"]):
            users_added.append(data["sender"])
            node_user = xml.createElement("user")
            node_user.setAttribute("name", data["sender"])
            node_user.setAttribute("role", data["sender_role"])
            node_user.setAttribute("group", data["sender_group"])
            node_user.setAttribute("weight", data["sender_weight"])
            node_users.appendChild(node_user)
        
        if data["receiver_type"] == 'user':
            if not users_added.__contains__(data["receiver"]):
                users_added.append(data["receiver"])
                node_receiver = xml.createElement("user")
                node_receiver.setAttribute("name", data["receiver"])
                node_receiver.setAttribute("role", data["receiver_role"])
                node_receiver.setAttribute("group", data["receiver_group"])
                node_receiver.setAttribute("weight", data["receiver_weight"])
                node_users.appendChild(node_receiver)
        elif not objects_added.__contains__(data["receiver"]):
            objects_added.append(data["receiver"])
            node_object = xml.createElement("object")
            node_object.setAttribute("name", data["receiver"])
            node_objects.appendChild(node_object)
        
        node_action = xml.createElement("action") #2005-12-30T20:49:25
        
        #nuevo
        #data["datetime"] = data["datetime"].replace('1899')
        
        try: dt = datetime.datetime.strptime(data["datetime"], '%Y-%m-%dT%H:%M:%S')
        except ValueError: 
            try: dt = datetime.datetime.strptime('2005-11-28T' + data["datetime"], '%Y-%m-%dT%I.%M:%S %p') #10.01:06 P.M
            except ValueError: 
                try: dt = datetime.datetime.strptime('2005-11-28T' + data["datetime"], '%Y-%m-%dT%I:%M:%S %p') #10.01:06 P.M
                except ValueError: dt = datetime.datetime.strptime('2005-11-28T' + data["datetime"], '%Y-%m-%dT%I:%M.%S %p') #10.01:06 P.M
        node_action.setAttribute("datetime", dt.strftime('%m/%d/%Y %H:%M:%S'))
        node_action.setAttribute("type", data["type"])
        node_action.setAttribute("weight", data["action_weight"])
        node_action.setAttribute("subtype", data["subtype"])
        node_action.setAttribute("channel", data["channel"])
        node_sender = xml.createElement("sender")
        node_sender.setAttribute("name", data["sender"])
        node_action.appendChild(node_sender)
        node_receiver = xml.createElement("receiver")
        node_receiver.setAttribute("name", data["receiver"])
        node_action.appendChild(node_receiver)
        node_actions.appendChild(node_action)
        
        if not events_added.__contains__(data["type"]):
            events_added.append(data["type"])
            node_event = xml.createElement("event")
            node_event.setAttribute("weight", data["event_weight"])
            node_event.setAttribute("type", data["type"])
            node_events.appendChild(node_event)
    
    if node_users is not None: node_activity.appendChild(node_users)
    if node_objects is not None: node_activity.appendChild(node_objects)
    if node_actions is not None: node_activity.appendChild(node_actions)
    if node_events is not None: node_activity.appendChild(node_events)
    node_situation.appendChild(node_activity)
    xml.appendChild(node_situation)
    

    fp = open(filename, "w")
    xml.writexml(fp, "\t", "\t", "\n", "UTF-8")



if __name__ == '__main__':
    #filenames_tq = ["ERHS", "FJRP", "MAEJ", "PGMA", "RLFV", "G10", "G09", "G08", "G07"]
    filenames_tq = ["Grupo2"]
    for filename in filenames_tq:
        datas = loadLogToActivity(filename)
        saveLogToActivity(filename, datas)
    
    print 'Finaliza exitosamente.'
    
